//拿到存放在session中某一列的id值
let id = sessionStorage.getItem("id");

$(function () {

    //将选中的一行数据填充到编辑页面
    $.ajax({
        url: 'http://localhost:11111/api/k/back/user/findById',
        headers:{"Authorization":"Bearer "+localStorage.getItem("token")},
        data: {id: id},
        dataType: 'json',

        success: function (res) {
            console.log("后端返回的数据", res)
            if (res.msg == "success") {
                //数据填充到选中修改的字段界面
                setData(res);
            } else {
                layer.alert("数据填充失败");
            }
        }
    })
})

//数据填充到选中修改的字段界面
function setData(res){

    layui.use(['form'], function () {
        let form = layui.form;
        let hobbies = res.data.hobby.split(",");
        console.log("爱好",hobbies);
        $("#L_username").val(res.data.username);
        $("#L_phone").val(res.data.phone);
        $("#L_email").val(res.data.email);



        //复选框
        $("input[type=checkbox][name=hobby]").each(function () {

            for (let i = 0; i < hobbies.length; i++) {
                if(hobbies[i] == $(this).attr("title")){
                    $(this).attr("checked",true);
                }
            }

        })
        //单选按钮，选中用prop
        if(res.data.enable == 1){
            $("input[type=radio][name=enable][value='启用']").prop("checked","checked");
        }else{
            $("input[type=radio][name=enable][value='停用']").prop("checked","checked");
        }
        $("#sex").val(res.data.sex)

        let date = new Date(res.data.birthday);
        let s = date.format("yyyy-MM-dd");

        $("#birthday").val(s)

        //一定要渲染一次,让数据填充成功
        form.render();

    })


}

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};


layui.use(['form', 'layer', 'jquery', 'laydate'],
    function () {
        $ = layui.jquery;
        var form = layui.form,
            layer = layui.layer;
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#birthday' //指定元素
            , trigger: 'click'
        });

        //自定义验证规则
        form.verify({
            nikename: function (value) {
                if (value.length < 5) {
                    return '昵称至少得5个字符啊';
                }
            }
        });

        //监听修改提交
        form.on('submit(edit)',
            function (data) {
                //定义存储复选框勾选的爱好内容
                let hobby = [];
                var attr = $('input[type="checkbox"][name="hobby"]:checked').each(function () {
                    hobby.push($(this).attr("title"));
                })
                data.field.hobby = hobby.toString();
                data.field.enable = (data.field.enable == '启用')?1:0;
                //js向对象中添加新的属性
                data.field.id  = id;
                // console.log(data.field);

                $.ajax({
                    url:"http://localhost:11111/api/k/back/user/update",
                    type:"post",
                    data:JSON.stringify(data.field),
                    contentType:"application/json",
                        headers:{"Authorization":"Bearer "+localStorage.getItem("token")},
                    dataType:"json",
                    success:function (res) {
                        if (res.msg == "success") {
                            //发异步，把数据提交给php
                            layer.alert("修改成功", {
                                    icon: 6
                                },
                                function () {
                                    //关闭当前frame
                                    xadmin.close();

                                    // 可以对父窗口进行刷新
                                    xadmin.father_reload();
                                });
                        } else {
                            layer.alert("修改失败");
                        }
                    }
                })



                return false;
            });

    });
function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function clearCookie(name) {
    setCookie(name, "", -1);
}
function clearAllCookie() {
    var date=new Date();
    date.setTime(date.getTime()-10000);
    var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
    console.log("需要删除的cookie名字："+keys);
    if (keys) {
        for (var i =  keys.length; i--;)
            document.cookie=keys[i]+"=0; expire="+date.toGMTString()+"; path=/";
    }
}
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
